package com.strelitzia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.strelitzia.dao.PhotoDao;
import com.strelitzia.entity.AlbumEntity;
import com.strelitzia.entity.PhotoEntity;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.AlbumService;
import com.strelitzia.service.PhotoService;
import com.strelitzia.utils.FileUtil;
import com.strelitzia.utils.TimeUtil;
import com.strelitzia.vo.PhotoItem;
import com.strelitzia.vo.UploadFrom;
import com.strelitzia.vo.UploadItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @create 2024/1/12 14:50
 */
@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoDao, PhotoEntity> implements PhotoService {
    @Autowired
    AlbumService albumService;

    @Override
    public void upload(UploadFrom uploadFrom) {
        if (uploadFrom.getFiles() != null) {
            Timestamp timestamp = new Timestamp(new Date().getTime());
            for (MultipartFile file : uploadFrom.getFiles()) {
                PhotoEntity photoEntity = new PhotoEntity();
                AlbumEntity albumEntity = albumService.getById(uploadFrom.getAlbumId());
                photoEntity.setAlbumName(albumEntity.getAlbumName());
                photoEntity.setAlbumId(uploadFrom.getAlbumId());
                photoEntity.setUid(CorsFilter.loginUserId.get());
                String src = FileUtil.fileUp(file);
                photoEntity.setSrc(src);
                albumEntity.setCover(src);
                photoEntity.setDelTag(0);
                photoEntity.setUploadTime(timestamp);
                this.save(photoEntity);
                albumEntity.setUpdateTime(photoEntity.getUploadTime());
                albumService.updateById(albumEntity);
            }
        }

    }

    @Override
    public List<PhotoItem> getList(Integer albumId) throws StrelitziaException {
        AlbumEntity byId = albumService.getById(albumId);
        if (byId == null) {
            throw new StrelitziaException("该相册不存在");
        }
        List<PhotoEntity> list = this.list(new QueryWrapper<PhotoEntity>()
                .eq("album_id", albumId)
                .eq("del_tag", 0)
                .orderByDesc("upload_time"));
        return getPhotoItems(list);
    }

    @Override
    public List<PhotoItem> getDelList() {
        List<PhotoEntity> list = this.list(new QueryWrapper<PhotoEntity>()
                .eq("uid", CorsFilter.loginUserId.get())
                .eq("del_tag", 1)
                .orderByDesc("upload_time"));
        return getPhotoItems(list);
    }

    @Override
    public void restore(Integer id) {
        PhotoEntity photoEntity = this.getById(id);
        AlbumEntity albumEntity = albumService.getOne(new QueryWrapper<AlbumEntity>()
                .eq("album_name", photoEntity.getAlbumName())
                .eq("uid", CorsFilter.loginUserId.get()));
        if (albumEntity == null) {
            albumService.create(photoEntity.getAlbumName());
            albumEntity = albumService.getOne(new QueryWrapper<AlbumEntity>()
                    .eq("album_name", photoEntity.getAlbumName())
                    .eq("uid", CorsFilter.loginUserId.get()));
        }
        photoEntity.setAlbumId(albumEntity.getId());
        photoEntity.setDelTag(0);
        this.updateById(photoEntity);
    }

    @Override
    public void clear() {
        this.remove(new QueryWrapper<PhotoEntity>()
                .eq("uid", CorsFilter.loginUserId.get())
                .eq("del_tag", 1));
    }

    @Override
    public void del(Integer id) {
        PhotoEntity photoEntity = this.getById(id);
        photoEntity.setDelTag(1);
        AlbumEntity albumEntity = albumService.getById(photoEntity.getAlbumId());
        albumEntity.setUpdateTime(new Timestamp(new Date().getTime()));
        albumService.updateById(albumEntity);
        this.updateById(photoEntity);
    }

    @Override
    public List<UploadItem> getAllList() {
        List<PhotoEntity> list = this.list(new QueryWrapper<PhotoEntity>()
                .eq("uid", CorsFilter.loginUserId.get())
                .eq("del_tag", 0)
                .orderByDesc("upload_time"));
        if (list != null) {
            List<UploadItem> uploadItems = new ArrayList<>();
            Timestamp timestamp = list.get(0).getUploadTime();
            List<String> src = new ArrayList<>();
            List<Integer> ids = new ArrayList<>();
            String name = "";
            Integer id = 0;
            for (PhotoEntity photoEntity : list) {
                if (!timestamp.equals(photoEntity.getUploadTime())) {
                    UploadItem uploadItem = new UploadItem();
                    uploadItem.setTime(timestamp.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy年 MM月dd日 hh时mm分")).replace(" ", "<br>"));
                    uploadItem.setSrc(src);
                    uploadItem.setId(id);
                    uploadItem.setAlbumName(name);
                    uploadItem.setIds(ids);
                    uploadItems.add(uploadItem);
                    timestamp = photoEntity.getUploadTime();
                    src = new ArrayList<>();
                    ids = new ArrayList<>();
                }
                src.add("/api/res/" + photoEntity.getSrc());
                ids.add(photoEntity.getId());
                name = photoEntity.getAlbumName();
                id = photoEntity.getAlbumId();
            }
            UploadItem uploadItem = new UploadItem();
            uploadItem.setTime(timestamp.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy年 MM月dd日 hh时mm分")).replace(" ", "<br>"));
            uploadItem.setSrc(src);
            uploadItem.setId(id);
            uploadItem.setAlbumName(name);
            uploadItem.setIds(ids);
            uploadItems.add(uploadItem);
            return uploadItems;
        } else {
            return new ArrayList<>();
        }


    }

    private List<PhotoItem> getPhotoItems(List<PhotoEntity> list) {
        if (list != null) {
            return list.stream().map(item -> {
                PhotoItem photoItem = new PhotoItem();
                photoItem.setSrc("/api/res/" + item.getSrc());
                photoItem.setId(item.getId());
                LocalDateTime time = item.getUploadTime().toLocalDateTime();
                photoItem.setTime(time.format(DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm:ss")));
                return photoItem;
            }).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }
}
